package com.tensquare.user.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
//自定义拦截器
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    //1.请求头处理，得到token，进而得到roles
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.先得到请求头
        String attribute = (String) request.getHeader("Authorization");
        //2.判断是否为空
        if(StringUtils.isNotBlank(attribute)){
            //2.1判断是否为bearer开头
            if(attribute.startsWith("Bearer ")){
                //2.2从第七位开始截取字符串来得到token
                String token = attribute.substring(7);
                //2.3调用工具类解析token
                Claims claims = jwtUtil.parseToken(token);
                //2.4判断claims不为空
                if(claims!=null){
                    request.setAttribute("claims",claims);
                }
            }
        }
        //3.放行
        return true;
    }
}
